<?php

class FnSvc
{
    const API_URL = 'https://exam-anubis.ele.me/anubis-webapi';
    const APP_ID = '04bdf897-12e9-42c0-904f-225e30e2bff4';    //填入正确的app_id
    const SECRET_KEY = 'a9555ac9-cf86-4077-abc1-2668722121eb';

      public function batchAudit(){
        $str = $_POST['id'];
        foreach ($str as $key=>$val){
            $sql = "update kfsy_pingtai.kf_drugstore_chain set ZT=2 where YID=$val and ZT=1";
            $arr = DB::update_db(1, $sql);
        }

        exit( json_encode(array("code"=>200,"msg"=>"'ok'")));
    }


    /*
     * 创建门店
     * */
    public function createStore($data,$id,$ptid){
        $url =self::API_URL."/v2/chain_store";
        $appid = self::APP_ID;
        $salt =self::getCode();
        $json = json_encode($data);
        $urlencodeData = urlencode($json);
        $token =  $this->requestToken();
        $sign = self::generateBusinessSign($appid, $token, $urlencodeData, $salt);
        $arr = json_encode(array(
            'app_id'=>$appid,
            'salt'=> $salt,
            'data'=>$urlencodeData,
            'signature'=>$sign
        ));
        $res = json_decode(self::doPost($url,$arr),true);
        if($res['code']==200){
            $sql = "insert into kfsy_pingtai.kf_drugstore_chain(PTID,YID,ZT)VALUES ($ptid,$id,1)";
            $arr = DB::insert_db(1, $sql);
        }else{
            $sql = "insert into kfsy_pingtai.kf_drugstore_chain(PTID,YID,ZT)VALUES ($ptid,$id,0)";
            $arr = DB::insert_db(1, $sql);
        }
        return $res;
    }

    /*
        创建订单信息
    */

    public function getCode(){
        return mt_rand(1000, 9999);
    }

    public function requestToken($salt="") {
        // 获取签名
        $salt = mt_rand(1000, 9999);
        $sig = self::generateSign(self::APP_ID, $salt, self::SECRET_KEY);
        $url = "https://exam-anubis.ele.me/anubis-webapi/get_access_token";
        $tokenStr = self::doGet($url, array('app_id' => self::APP_ID, 'salt' => $salt, 'signature' => $sig));
        // echo $tokenStr;
        // 获取token
        $token = json_decode($tokenStr, true);
        return $token['data']['access_token'];

    }


    public static function generateSign($appId, $salt, $secretKey) {
        $seed = 'app_id=' . $appId . '&salt=' . $salt . '&secret_key=' . $secretKey;
        return md5(urlencode($seed));
    }

    public static function generateBusinessSign($appId, $token, $urlencodeData, $salt)
    {
        $seed = 'app_id=' . $appId . '&access_token=' . $token
            . '&data=' . $urlencodeData . '&salt=' . $salt;
        return md5($seed);
    }

    public static function doPost($url, $param, $method = "POST")
    {
        // echo 'Request url is ' . $url . PHP_EOL;
        if (empty($url) or empty($param)) {
            throw new InvalidArgumentException('Params is not of the expected type');
        }

        // 验证url合法性
//        if (!filter_var($url, FILTER_VALIDATE_URL)) {
//            throw new InvalidArgumentException('Url is not valid');
//        }

        if (!empty($param) and is_array($param)) {
            $param = urldecode(json_encode($param));
        } else {
            // $param = urldecode(strval($param));
            $param = strval($param);
        }

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        // curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);     //  不进行ssl 认证

        if (strcmp($method, "POST") == 0) {  // POST 操作
            curl_setopt($ch, CURLOPT_POST, true);
        } else if (strcmp($method, "DELETE") == 0) { // DELETE操作
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        } else {
            throw new InvalidArgumentException('Please input correct http method, such as POST or DELETE');
        }

        curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: Application/json'));
        $result = curl_exec($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if (!empty($result) and $code == '200') {
            return $result;
        }
        return false;
    }





    public static function doGet($url, $param = null)
    {
        if (empty($url) or (!empty($param) and !is_array($param))) {
            throw new InvalidArgumentException('Params is not of the expected type');
        }
        // 验证url合法性
//        if (!filter_var($url, FILTER_VALIDATE_URL)) {
//            throw new InvalidArgumentException('Url is not valid');
//        }

        if (!empty($param)) {
            $url = trim($url, '?') . '?' . http_build_query($param);
        }

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_AUTOREFERER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);     //  不进行ssl 认证
        // curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        $result = curl_exec($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if (!empty($result) and $code == 200) {
            return $result;
        }
        return false;
    }


    /*
        创建订单
        params
            partner_remark 订单备注
            partner_order_code 订单编号
            transport_info 商户门店信息

    */
    public function createOrder()
    {
        # code...
    }

    /*
        生成商户信息
        params
            transport_name 门店名称
            transport_address 取货点地址 
            transport_longitude 取货点经度，取值范围0～180
            transport_latitude 取货点纬度，取值范围0～90
            transport_tel 取货点联系方式, 只支持手机号,400开头电话以及座机号码
            transport_remark 取货点备注
    */
    public function createTransportInfo($transport_name = '', $transport_address = '', $transport_longitude = '', $transport_latitude = '', $transport_tel = '', $transport_remark = '')
    {
        $data = array();
        $data['transport_name'] = $transport_name;
        $data['transport_address'] = $transport_address;
        $data['transport_longitude'] = $transport_longitude;
        $data['transport_latitude'] = $transport_latitude;
        $data['position_source'] = 3; //取货点经纬度来源, 1:腾讯地图, 2:百度地图, 3:高德地图
        $data['transport_tel'] = $transport_tel;
        $data['transport_remark'] = $transport_remark;

        return $data;
    }
}